<template>
  <div>
    <el-button type="danger" :icon="Plus" style="float: left; margin-left: 10px"
      >新增</el-button
    >&emsp;
    <el-button
      type="danger"
      :icon="Check"
      style="float: left; margin-left: 10px"
      @click="save()"
      >保存</el-button
    >&emsp;
    <el-button type="danger" :icon="Back" style="float: left; margin-left: 10px"
      >撤销</el-button
    >&emsp;
    <el-button
      type="danger"
      :icon="Delete"
      style="float: left; margin-left: 10px"
      >删除</el-button
    >
  </div>
  <br />
  <div>
    <span style="font-weight: bold">负责人</span>&emsp;
    <el-select v-model="form.leader" placeholder="-- --" style="width: 240px">
      <el-option label="罗翔" value="罗翔" />
      <el-option label="杨家霖" value="杨家霖" />
      <el-option label="雷鑫" value="雷鑫" />
      <el-option label="王丹青" value="王丹青" />
      <el-option label="温媛媛" value="温媛媛" />
      <el-option label="杨杰" value="杨杰" />
      <el-option label="赵丽" value="赵丽" />
      <el-option label="黄强" value="黄强" />
      <el-option label="吴敏" value="吴敏" />
      <el-option label="周亮" value="周亮" />
      <el-option label="徐蕾" value="徐蕾" />
      <el-option label="孙伟" value="孙伟" />
      <el-option label="李霞" value="李霞" />
      <el-option label="马超" value="马超" />
      <el-option label="郭丽" value="郭丽" />
      <el-option label="高峰" value="高峰" />
      <el-option label="何敏" value="何敏" />
      <el-option label="林静" value="林静" />
      <el-option label="罗文" value="罗文" />
      <el-option label="蒋娜" value="蒋娜" />
    </el-select>
    <span style="font-weight: bold"> 妊检日期:</span>&emsp;
    <el-date-picker
      v-model="form.pregnancyTestDate"
      type="date"
      placeholder="日期"
      :default-value="new Date()"
      style="width: 150px"
      value-formate="YYYY-MM-DD"
    />
    单据号:<el-input
      v-model="form.documentNo"
      style="width: 180px"
      disabled
    ></el-input
    >流水号:<el-input v-model="form.serialNo" style="width: 180px" disabled>
    </el-input>
  </div>
  <br />
  <hr style="font-size: 20px" />
  <br />
  <div class="table-container" style="height: 400px; position: relative">
    <table style="border-collapse: collapse">
      <tr>
        <td>序号</td>
        <td>耳号</td>
        <td>妊检结果</td>
        <td>妊检方式</td>
        <td>同胎数</td>
        <td>妊娠天数</td>
        <td>当前栋舍</td>
        <td>当前栏位</td>
        <td>转入栋舍</td>
        <td>转入栏位</td>
        <td>操作</td>
      </tr>
      <tr v-for="(ruleForm, index) in loge.healthArray">
        <td>
          {{ index + 1 }}
        </td>
        <td style="width: 150px">
          <el-select v-model="ruleForm.earNo" placeholder="耳号">
            <el-option
              v-for="item in sleepInfoDatas.filter((x:any)=>x.gender==2&&x.checkPre==null)"
              :label="item.earNumber"
              :value="item.sleepInforId"
              @click="getearMsg(index)"
            />
          </el-select>
        </td>
        <td>
          <el-select
            v-model="ruleForm.pregnancyTestResult"
            placeholder="妊检结果"
          >
            <el-option
              v-for="item in fieldsDatass"
              :label="item.pregnancyTestResultName"
              :value="item.pregnancyTestResult"
              @click="resultCheck(item.pregnancyTestResult,index)"
            />
          </el-select>
        </td>
        <td style="width: 150px">
          <el-select
            v-model="ruleForm.pregnancyTestMethod"
            placeholder="妊检方式"
          >
            <el-option
              v-for="item in fieldsDatas"
              :label="item.pregnancyCheckMethodName"
              :value="item.pregnancyCheckMethodId"
            />
          </el-select>
        </td>
        <td>
          <el-input v-model="ruleForm.litterCount"></el-input>
        </td>
        <td>
          <el-input v-model="ruleForm.pregnancyDays"></el-input>
        </td>
        <td>
          <el-select
            style="width: 100px"
            v-model="ruleForm.currentBarn"
            placeholder="请选择"
          >
            <el-option
              v-for="item in Recordcottage"
              :label="item.cottageName"
              :value="item.cottagesId"
            />
          </el-select>
        </td>
        <td>
          <el-select
            style="width: 100px"
            v-model="ruleForm.currentPen"
            placeholder="请选择"
          >
            <el-option
              v-for="item in Fields"
              :label="item.fieIdName"
              :value="item.fieIdId"
            />
          </el-select>
        </td>
        <td>
          <el-select
            style="width: 100px"
            v-model="ruleForm.transferBarn"
            placeholder="请选择"
          >
            <el-option
              v-for="item in Recordcottage2"
              :label="item.cottageName"
              :value="item.cottagesId"
              @click="getFields2(ruleForm.transferBarn, index)"
            />
          </el-select>
        </td>
        <td>
          <el-select
            style="width: 100px"
            v-model="ruleForm.transferPen"
            placeholder="请选择"
          >
            <el-option
              v-for="item in Fields2[index]"
              :label="item.fieIdName"
              :value="item.fieIdId"
            />
          </el-select>
        </td>
        <td>
          <el-link :underline="false" type="primary" @click="inithealth(index)"
            >保存</el-link
          >
          <el-link
            :underline="false"
            type="primary"
            @click.prevent="beginDel(index)"
          >
            移除
          </el-link>
        </td>
      </tr>
    </table>
  </div>

  <div style="bottom: 0; left: 0; width: 100%">
    <hr />
    <!-- <span>&emsp; 合计</span>
            <hr> -->
    <el-button
      link
      type="danger"
      :icon="Plus"
      style="float: left; margin-left: 10px"
      @click="addDomain"
      >增行</el-button
    >&emsp;
    <el-button
      link
      type="danger"
      :icon="Check"
      style="float: left; margin-left: 10px"
      @click="delDomain"
      >删行</el-button
    >&emsp;
    <br />
    <hr />
    <span style="vertical-align: top; width: 5%">&emsp; 备注</span>&emsp;
    <el-input v-model="form.notes" type="textarea" style="width: 85%" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useCounterStore } from '@/stores/counter';
import { Check, Delete, Plus, Back } from '@element-plus/icons-vue';
const counterStore = useCounterStore();
const route = useRoute();
const router = useRouter();
const loge = reactive({
  healthArray: <any>[],
});

const tableData = ref([]);
const ruleForm = reactive({
  notes: '',
});
const numbers = ref(1);
//增行
const addDomain = () => {
  loge.healthArray.push(
    reactive({
      ewePregnancyCheckRecordId: 0,
      leader:form.leader,
      pregnancyTestDate: new Date(),
      earNo: '',
      pregnancyTestResult: '',
      pregnancyTestMethod: '',
      litterCount: '',
      pregnancyDays: '',
      currentBarn: '',
      currentPen: '',
      transferBarn: '',
      transferPen: '',
      notes: form.notes || 0,
      documentNo: form.documentNo,
      serialNo: form.serialNo,
      deletes: true,
      createId:form.createId
    })
  );
  console.log(loge.healthArray);
};

const form = reactive({
  leader:'',
  pregnancyTestDate: '',
  documentNo:'',
  serialNo: '',
  notes: '',
  createId:localStorage.getItem('aaa')
  // BreedStatuId:''
});
//妊检日期


const resultCheck=(id:any,index:any)=>{
  console.log(id)
  if(id==4){
    console.log(new Date())
    console.log(form.pregnancyTestDate)
    loge.healthArray[index].pregnancyDays=Math.ceil((new Date()-form.pregnancyTestDate)/1000/60/60/24)
    
    
  }else{
    loge.healthArray[index].pregnancyDays=0

  }
}

//减行
const delDomain = () => {
  loge.healthArray.splice(loge.healthArray.length - 1, 1);
};
//保存

//单据号
// const documentNo = ref('');
// //流水号
// const serialNo = ref('');

const inithealth = (index: number) => {
  console.log(loge.healthArray[index]);
  console.log(loge.healthArray.pregnancyDays)
  axios
    .post( 
      'http://localhost:5039/api/ProductionManagement/Handle',
      loge.healthArray[index]
    )
    .then((res) => {
      console.log(res)
      if (res.data.code > 0) {
        ElMessage.success('种母妊检信息添加成功');
        getIds1();
        getIds2();
        router.push('/Mother_breedingList');
      } else {
        ElMessage.error('种母妊检信息添加失败');
      }
    });
  loge.healthArray.splice(index, 1);
};

//获取养只信息
const updates = reactive({
  eweID: '',
  currentBarn: '',
  currentPen: '',
});

//移除
const beginDel = (index: any) => {
  loge.healthArray.splice(index, 1);
  numbers.value++;
};

//获取雪花id(单据号、流水号)
const getIds1 = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/GetId', {})
    .then((res) => {
      console.log(res)
      form.documentNo = res.data.toString();
    });
};

const getIds2 = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/GetId', {})
    .then((res) => {
      form.serialNo = res.data.toString();
    });
};

const getearMsg = (index: any) => {
  const selectedEweID = loge.healthArray[index].earNo;
  console.log(selectedEweID);
  axios
    .get('http://localhost:5039/api/ProductionManagement/EarMasList', {
      params: {
        SleepInforId: selectedEweID,
        BreedStatuId: 4,
      },
    })
    .then((res) => {
      console.log(res.data.item);
      updates.eweID = res.data.item.sleepInforId;
      updates.currentBarn = res.data.item.recordcottageId;
      updates.currentPen = res.data.item.fieIdId;
      handleUpdate(); //调用更新数据的方法
    });
};

const handleUpdate = () => {
  const eweID = updates.eweID; // 假设你从表单获取到的 EweID
  const currentBarn = updates.currentBarn; // 假设你从表单获取到的 CurrentBarn
  const currentPen = updates.currentPen; // 假设你从表单获取到的 CurrentPen
  console.log(eweID, currentBarn, currentPen);
  updateFieldsByEweID(eweID, currentBarn, currentPen);
};

const updateFieldsByEweID = (
  eweID: string,
  currentBarn: string,
  currentPen: string
) => {
  // 遍历 healthArray 找到 EweID 对应的项并更新
  console.log(loge.healthArray);
  const healthItem = loge.healthArray.find((item: any) => item.earNo === eweID);

  if (healthItem) {
    healthItem.currentBarn = currentBarn;
    getFields(healthItem.currentBarn);

    healthItem.currentPen = currentPen;
  } else {
    console.log(`没有找到EweID为 ${eweID} 的数据`);
  }
};

//获取耳号下拉信息
const sleepInfoDatas: any = ref([]);
const getSleepInfos = () => {
  axios
    .get('http://localhost:5039/api/SleepBegin/SelectEarFeMale')
    .then((res) => {
      console.log(res);
      sleepInfoDatas.value = res.data.data;
    });
};

//获取妊检方式
const fieldsDatas: any = ref([]);
const getMethod = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/Handle6')
    .then((res) => {
      console.log(res.data.data);
      fieldsDatas.value = res.data.data;
    });
};

//获取妊检结果
const fieldsDatass: any = ref([]);
const getMethods = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/Handle5')
    .then((res) => {
      console.log(res.data.data);
      fieldsDatass.value = res.data.data;
    });
};

//获取栋舍
const Recordcottage = ref<any>([]);
const Recordcottage2 = ref<any>([]);
const getRecordcottage = () => {
  axios
    .post('http://localhost:5039/api/Cottages/CottageList', {})
    .then((res) => {
      Recordcottage.value = res.data.data;
      Recordcottage2.value = res.data.data;
    });
};
//获取栏位
const Fields = ref<any>([]);
const Fields2 = ref<any>([]);
const getFields = (id: number) => {
  console.log(id);
  axios
    .post('http://localhost:5039/api/Cottages/SearchFields', {
      cottagesId: id,
      pageIndex: 1,
      pageSize: 100000000,
    })
    .then((res) => {
      console.log(res.data.data);
      Fields.value = res.data.data;
    });
};
const getFields2 = (id: number, index: any) => {
  Fields2.value[index] = [];
  axios
    .post('http://localhost:5039/api/Cottages/SearchFields', {
      cottagesId: id,
      pageIndex: 1,
      pageSize: 100000000,
    })
    .then((res) => {
      Fields2.value[index] = res.data.data;
      loge.healthArray[index].transferPen = '';
      console.log(Fields2.value);
    });
};

//获取妊检结果

onMounted(() => {
  getIds1();
  getIds2();
  getSleepInfos();
  getMethod();
  getMethods();
  getRecordcottage(); //栋舍
});
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 设置第一行的 td 顶部边框加粗并设置为红色 */
table tr:first-child td {
  border-top: 3px solid red;
  /* 设置顶部边框为3px宽度的红色 */
  padding: 10px;
  text-align: center;
}

/* 设置 td 的样式 */

table td {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: center;
  font-size: 14px;
  height: 60px;
  width: 150px;
  white-space: nowrap;
  /* 防止内容换行 */
}

/* 可选：为 table 添加样式 */
table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

/*______________________________________________________*/

.table-container {
  max-width: 100%;
  overflow-x: auto;
  /* 启用水平滚动 */
  margin: 20px 0;
  /* 设置容器的外边距 */
}
</style>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 设置第一行的 td 顶部边框加粗并设置为红色 */
table tr:first-child td {
  border-top: 3px solid red;
  /* 设置顶部边框为3px宽度的红色 */
  padding: 10px;
  text-align: center;
}

/* 设置 td 的样式 */

table td {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: center;
  font-size: 14px;
  height: 60px;
  width: 150px;
  white-space: nowrap;
  /* 防止内容换行 */
}

/* 可选：为 table 添加样式 */
table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

/*______________________________________________________*/

.table-container {
  max-width: 100%;
  overflow-x: auto;
  /* 启用水平滚动 */
  margin: 20px 0;
  /* 设置容器的外边距 */
}
</style>
